<template>
	<view class="container">
		<uni-search-bar
			class="search-bar"
			@confirm="onSearch"
			:focus="true"
			v-model="keyword"
			@focus="onFocus"
			@input="onInput"
			@cancel="cancelSearch"
			@clear="clearKeyword"
			radius="100"
		></uni-search-bar>

		<!-- 搜索建议 -->
		<view class="suggestions" v-if="showSuggestions && suggestions.length > 0">
			<view class="suggestion-item" v-for="(item, index) in suggestions" :key="index" @click="selectSuggestion(item)">
				<uni-icons type="search" size="14" color="#999" class="mr-2"></uni-icons>
				<text>{{ item }}</text>
			</view>
		</view>

		<!-- 搜索历史 -->
		<view class="history-container" v-if="showHistory">
			<view class="history-header">
				<text class="title">搜索历史</text>
				<view class="clear-btn" @click="clearHistory" v-if="searchHistory.length > 0">
					<uni-icons type="trash" size="14" color="#999"></uni-icons>
					<text class="ml-1">清空历史</text>
				</view>
			</view>
			<view class="history-tags" v-if="searchHistory.length > 0">
				<view class="tag" v-for="(item, index) in searchHistory" :key="index" @click="selectHistory(item)">
					<text>{{ item }}</text>
				</view>
			</view>
			<view class="empty-history" v-else>
				<text>暂无搜索历史</text>
			</view>
		</view>

		<!-- 搜索结果 -->
		<view class="result-container" v-if="showResult">
			<!-- 加载状态 -->
			<view class="loading" v-if="isLoading">
				<uni-load-more
					status="loading"
					:contentText="{
						loading: '加载中...',
						end: '没有更多数据了',
						error: '加载失败，请重试'
					}"
				></uni-load-more>
			</view>

			<!-- 空结果状态 -->
			<view class="empty-result" v-else-if="products.length === 0">
				<image src="/static/images/empty-search.png" mode="aspectFit"></image>
				<text class="mt-3">没有找到与"{{ keyword }}"相关的商品</text>
				<button class="retry-btn" type="default" @click="clearKeyword">重新搜索</button>
			</view>
	  
			<!-- 商品列表 -->
			<view class="product-container" >
				<!-- 	左边栏 -->
				<view class="product-grid" >
					<view class="product-card" v-for="(product, index) in productList.left" :key="index" v-show="productList.left.length>0">
				   <shopProductCard :product="product"></shopProductCard>
					</view>
				</view>
				<!-- 右边栏 -->
				<view class="product-grid" >
					<view class="product-card" v-for="(product, index) in productList.right" :key="index" v-show="productList.right.length>0">
					
                     <shopProductCard :product="product"></shopProductCard>
					

						</view>
					</view>
				</view>
		  </view>
	
		<movable-area :style="{width: systemInfo.windowWidth + 'px',height: systemInfo.windowHeight + 'px', position: 'fixed',left: 0,zIndex: 9999,pointerEvents: 'none'}">
			<movable-view direction="all" style="pointer-events: auto;" x="500" y="800">
			<RightBar :bottom="550+keyboardHeight+'rpx'" ></RightBar>
			</movable-view>
		</movable-area>
	</view>
</template>

<script>
const order=uniCloud.importObject('order',{customUI:true})
import shopProductCard from '../../components/shop/shopProductCard/shopProductCard.vue';
import RightBar from '../../components/RightBar.vue';
export default {
	components:{
		shopProductCard,
		RightBar
	},
	data() {
		return {
			keyword: '',
			searchHistory: [],
			suggestions: [],
			products: [],
			isLoading: false,
			showHistory: true,
			showResult: true,
			showSuggestions: false,
			timer: null,
			category: '',
			minPrice: 0,
			maxPrice: 999999,
			page: 1,
			pageSize: 20,
			groupId: '',
			keyboardListen:null,
			keyboardHeight:0
			
		};
	},
	computed:{
		productList(){
		const left=[]
		const right=[]
		this.products.forEach((item,index)=>{
			if(index%2===0){
				left.push(item)
			}else{
				right.push(item)
			}
			
		})
		return {left,right}
	},
		systemInfo(){
			return this.$store.state.msg.systemInfo
		}
	},

	onLoad(res) {
		// 从本地存储加载搜索历史
		this.keyboardListen = (result) => {
			this.keyboardHeight = result.height*(750/this.systemInfo.windowWidth);
		
		};
		uni.onKeyboardHeightChange(this.keyboardListen);
		this.loadSearchHistory();
		this.groupId = res.groupId;
	},
	beforeDestroy() {
	 uni.offKeyboardHeightChange(this.keyboardListen)	
	},
	methods: {
		// 加载搜索历史
		loadSearchHistory() {
			try {
				const history = uni.getStorageSync('search_history');
				if (history) {
					this.searchHistory = JSON.parse(history);
				}
			} catch (e) {
				console.error('Failed to load search history:', e);
			}
		},

		// 保存搜索历史
		saveSearchHistory(keyword) {
			const pureKeyword = keyword.trim(); // 去除前后空格
			if (!pureKeyword) return;

			// 去重：忽略空格差异，不区分大小写（可选，根据需求调整）
			this.searchHistory = this.searchHistory.filter((item) => item.trim().toLowerCase() !== pureKeyword.toLowerCase());

			this.searchHistory.unshift(pureKeyword); // 存入处理后的关键词
			if (this.searchHistory.length > 10) {
				this.searchHistory = this.searchHistory.slice(0, 10);
			}

			try {
				uni.setStorageSync('search_history', JSON.stringify(this.searchHistory));
			} catch (e) {
				console.error('Failed to save search history:', e);
			}
		},

		// 输入事件处理
		onInput(e) {
			console.log('11111', e);
			// 正确获取输入值：e.detail.value（UniApp 组件统一的参数格式）
			this.keyword = e;

			if (this.keyword) {
				this.showHistory = false;
				this.showResult = false;
				this.showSuggestions = true;

				// 防抖处理（保留原逻辑，修复参数后生效）
				clearTimeout(this.timer);
				this.timer = setTimeout(() => {
					this.getSuggestions(this.keyword);
				}, 300);
			} else {
				this.showHistory = true;
				this.showResult = false;
				this.showSuggestions = false;
			}
		},

		// 获取搜索建议
		getSuggestions(keyword) {
			uniCloud
				.callFunction({
					name: 'getSuggestions',
					data: { keyword: keyword }
				})
				.then((res) => {
					this.suggestions = res.result.data;
					console.log(this.suggestions);
				})
				.catch((e) => {
					console.log(e);
				});
		},

		// 输入框聚焦事件
		onFocus() {
			if (this.keyword) {
				this.showHistory = false;
				this.showResult = false;
				this.showSuggestions = true;
				this.getSuggestions(this.keyword);
			} else {
				this.showHistory = true;
				this.showResult = false;
				this.showSuggestions = false;
			}
		},

		// 搜索确认
		// 1. 当前搜索页：onSearch 优化（确保异步完成后再操作）
		async onSearch() {
			if (!this.keyword.trim()) return;

			this.showHistory = false;
			this.showSuggestions = false;
			this.showResult = true;
			this.isLoading = true;

			try {
				// 1. 保存搜索历史
				this.saveSearchHistory(this.keyword);
				// 2. 异步获取结果（等待完成）
				const searchRes = await this.searchProducts(this.keyword);
				this.products = searchRes;
				this.isLoading = false;
                console.log("搜索结果",searchRes);
				//3. 发送事件（确保结果已更新）
				//uni.$emit('searchResult', searchRes);
				// 4. 延迟返回（给事件传递留时间，兼容低性能设备）
		
			} catch (e) {
				this.isLoading = false;
				uni.showToast({ title: '搜索失败，请重试', icon: 'none' });
				console.error('搜索错误:', e);
			}
		},

		// 2. 上一页（接收结果的页面）：在 onShow 中监听事件（避免页面缓存导致监听失效）

		// 搜索商品
		async searchProducts(keyword) {
	
			const data = {
				keyword: keyword,
				category: this.category,
				minPrice: this.minPrice,
				maxPrice: this.maxPrice,
				page: this.page,
				pageSize: this.pageSize,
			
			};
			console.log(data);
			const res=await order.getProduct(data)
			if(res.success){
				return res.products;
			}else{
				return []
			}
		 
			
		},

		// 选择历史记录
		selectHistory(keyword) {
			this.keyword = keyword;
			this.onSearch();
		},

		// 选择搜索建议
		selectSuggestion(suggestion) {
			this.keyword = suggestion;
			this.onSearch();
		},

		// 清除关键词
		clearKeyword() {
			this.keyword = '';
			this.showHistory = true;
			this.showResult = false;
			this.showSuggestions = false;
		},

		// 取消搜索
		cancelSearch() {
			uni.navigateBack();
		},

		// 清除历史记录
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清除搜索历史吗？',
				success: (res) => {
					if (res.confirm) {
						this.searchHistory = [];
						try {
							uni.removeStorageSync('search_history');
						} catch (e) {
							console.error('Failed to clear search history:', e);
						}
					}
				}
			});
		},
		getQuantity(productId) {
			const items = this.$store?.state?.cart?.items || [];
			const item = items.find((item) => item._id === productId);
			return item?.quantity || 0;
		},
		changeQuantity(item, delta) {
			uni.vibrateShort({});
			const currentQty = this.getQuantity(item._id);
		
			if (currentQty === 0) {
				// 新增商品到购物车
				this.$store.commit('cart/addItem', { ...item, quantity: 1 });
			} else {
				const newQty = currentQty + delta;
				if (newQty > 0) {
					// 更新数量
					this.$store.commit('cart/updateQuantity', {
						id: item._id,
						quantity: newQty
					});
				} else {
					// 移除商品
					this.$store.commit('cart/removeItem', item._id);
				}
			}
		},
		

		// 跳转到商品详情
		goToProductDetail(id) {
			uni.navigateTo({
				url: `/pages/product/detail?id=${id}`
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	background-color: #f8f8f8;
	min-height: 100vh;
	min-width: 100vw;
}
.product-container{
	  display: flex;
	  padding: 10rpx 20rpx; /* 用 rpx 适配不同屏幕，避免 px 固定值 */
	  gap: 20rpx; /* 两列间距，用 rpx 更适配 */
	  width: 100vw;
	  box-sizing: border-box; /* 关键：padding 不影响总宽度 */
	  flex-wrap: nowrap; /* 强制两列不换行（因只需两列） */
	
}
.product-card {
  width: 100%; /* 关键：卡片占满列宽 */
  box-sizing: border-box; /* 避免内部 padding 导致宽度超界 */
  /* 可选：若卡片有边框/内边距，加在这里，不影响宽度计算 */
  padding: 10rpx;
  border-radius: 12rpx;
}
.product-grid {
  flex: 1; /* 关键：两列各占 50% 宽度（flex:1 会平分剩余空间） */
  box-sizing: border-box; /* 避免 padding/margin 挤压宽度 */
  /* 可选：若需额外内边距，加 padding 但不影响总宽度 */
  padding: 0 5rpx; 
}
/* 搜索栏 */
.search-bar {
	display: flex;
	align-items: center;
	padding: 10px 15px;
	background-color: #fff;
	border-bottom: 1px solid #eee;

	.search-box {
		flex: 1;
		display: flex;
		align-items: center;
		height: 32px;
		padding: 0 10px;
		background-color: #f5f5f5;
		border-radius: 16px;

		.search-icon {
			margin-right: 5px;
		}

		input {
			flex: 1;
			height: 100%;
			font-size: 14px;
			color: #333;

			.placeholder {
				color: #999;
			}
		}

		.clear-icon {
			padding: 3px;
			cursor: pointer;
		}
	}

	.cancel-btn {
		width: 50px;
		text-align: center;
		color: #007aff;
		font-size: 14px;
		cursor: pointer;
	}
}

/* 搜索建议 */
.suggestions {
	background-color: #fff;
	border-bottom: 1px solid #eee;

	.suggestion-item {
		display: flex;
		align-items: center;
		padding: 10px 15px;
		font-size: 14px;
		color: #333;
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		&:hover {
			background-color: #f8f8f8;
		}
	}
}

/* 搜索历史 */
.history-container {
	padding: 15px;
	background-color: #fff;

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 30px;

		.title {
			font-size: 14px;
			color: #333;
			font-weight: 500;
		}

		.clear-btn {
			display: flex;
			align-items: center;
			color: #999;
			font-size: 12px;
			cursor: pointer;
		}
	}

	.history-tags {
		display: flex;
		flex-wrap: wrap;
		padding-top: 10px;

		.tag {
			padding: 5px 12px;
			margin-right: 10px;
			margin-bottom: 10px;
			background-color: #f5f5f5;
			border-radius: 15px;
			font-size: 12px;
			color: #666;
			cursor: pointer;

			&:hover {
				background-color: #eee;
			}
		}
	}

	.empty-history {
		padding: 20px 0;
		text-align: center;
		color: #999;
		font-size: 13px;
	}
}

/* 搜索结果 */
.result-container {
	padding: 10px;

	.loading {
		padding: 20px 0;
		text-align: center;
	}

	.empty-result {
		padding: 40px 0;
		text-align: center;

		image {
			width: 120px;
			height: 120px;
			opacity: 0.6;
		}

		text {
			display: block;
			margin-top: 15px;
			color: #999;
			font-size: 14px;
		}

		.retry-btn {
			width: 120px;
			height: 32px;
			line-height: 32px;
			margin-top: 20px;
			padding: 0;
			font-size: 14px;
			background-color: #ff4d4f;
			color: #fff;
			border-radius: 16px;
		}
	}

	.product-list {
		display: flex;
		flex-wrap: wrap;

		.product-item {
			width: calc(50% - 5px);
			margin-bottom: 10px;
			background-color: #fff;
			border-radius: 8px;
			overflow: hidden;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

			&:nth-child(odd) {
				margin-right: 10px;
			}

			.product-image-wrapper {
				position: relative;
				width: 100%;
				height: 0;
				padding-bottom: 100%;

				.product-image {
				  width: 100%;
				  height: auto; /* 高度自动按比例缩放 */
				}

				.product-tag {
					position: absolute;
					top: 5px;
					left: 5px;
					background-color: #ff4d4f;
					color: #fff;
					font-size: 10px;
					padding: 1px 4px;
					border-radius: 3px;
				}
			}

			.product-info {
				padding: 8px;

				.product-name {
					  display: -webkit-box;
					  -webkit-line-clamp: 2;
					  -webkit-box-orient: vertical;
					  overflow: hidden;
					  text-overflow: ellipsis;
					  line-height: 32rpx;
					  height: 64rpx;
				}

				.product-price {
					display: block;
					margin-top: 5px;
					font-size: 15px;
					font-weight: 500;
					color: #ff4d4f;
				}

				.product-sold {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 3px;
					font-size: 11px;
					color: #999;

					.rating {
						display: flex;
						align-items: center;
					}
				}
			}
		}
	}
}
</style>
